<template>
  <div class="export-container">
    <div class="export-header">
      <button
          @click="goBack()"
          class="btn btn-secondary"
      >
        <i class="fas fa-arrow-left" style="margin-right: 5px;"></i>
        返回列表
      </button>
      <h2 class="page-title">
        <i class="fas fa-file-export" style="color: #42b983; margin-right: 10px;"></i>
        简历导出
      </h2>
      <div class="export-actions">
        <button
            @click="exportAllAsWord()"
            class="btn btn-primary"
            :disabled="loading || resumes.length === 0"
        >
          <i class="fas fa-file-word" style="margin-right: 5px;"></i>
          导出全部为Word
        </button>
        <button
            @click="exportAllAsPDF()"
            class="btn btn-success"
            :disabled="loading || resumes.length === 0"
            style="margin-left: 10px;"
        >
          <i class="fas fa-file-pdf" style="margin-right: 5px;"></i>
          导出全部为PDF
        </button>
      </div>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading-container">
      <i class="fas fa-spinner fa-spin" style="font-size: 36px; color: #42b983;"></i>
      <div class="loading-text">加载中...</div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-container">
      <i class="fas fa-exclamation-circle" style="font-size: 36px; color: #ff4d4f;"></i>
      <div class="error-text">{{ error }}</div>
      <button
          @click="fetchResumes()"
          class="btn btn-primary"
          style="margin-top: 20px;"
      >
        <i class="fas fa-sync-alt" style="margin-right: 5px;"></i>
        重试
      </button>
    </div>

    <!-- 简历列表 -->
    <div v-if="!loading && !error" class="resume-list">
      <div v-if="resumes.length === 0" class="empty-container">
        <i class="fas fa-file-alt" style="font-size: 64px; color: #ccc; margin-bottom: 20px;"></i>
        <div class="empty-text">暂无简历数据</div>
        <div class="empty-hint">请先创建简历后再进行导出</div>
      </div>

      <div v-else class="resume-cards">
        <div
            v-for="resume in resumes"
            :key="resume.id"
            class="resume-card"
        >
          <div class="card-header">
            <div class="card-title">
              <h3>{{ resume.name }}</h3>
              <span class="card-badge">{{ resume.education }}</span>
            </div>
            <div class="card-actions">
              <button
                  @click="exportSingleAsWord(resume)"
                  class="btn btn-sm btn-primary"
                  title="导出为Word"
              >
                <i class="fas fa-file-word"></i>
              </button>
              <button
                  @click="exportSingleAsPDF(resume)"
                  class="btn btn-sm btn-danger"
                  title="导出为PDF"
                  style="margin-left: 8px;"
              >
                <i class="fas fa-file-pdf"></i>
              </button>
            </div>
          </div>
          <div class="card-body">
            <div class="info-row">
              <span class="info-label">期望职位：</span>
              <span class="info-value">{{ resume.expectedJob }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">应届年份：</span>
              <span class="info-value">{{ resume.graduate_year || "无" }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">手机号：</span>
              <span class="info-value">{{ resume.phone }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">简历评分：</span>
              <span class="info-value">{{ resume.resume_score || 0 }}分</span>
            </div>
            <div class="info-tags">
              <span class="tag">工作经历：{{ (resume.work_experiences || []).length }}条</span>
              <span class="tag">项目经历：{{ (resume.project_experiences || []).length }}条</span>
              <span class="tag">教育经历：{{ (resume.education_experiences || []).length }}条</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

// 延迟加载html2pdf.js（按需导入）
let html2pdf = null;
const loadHtml2Pdf = async () => {
  if (!html2pdf) {
    try {
      const module = await import('html2pdf.js');
      html2pdf = module.default || module;
    } catch (err) {
      console.error('加载html2pdf.js失败:', err);
      throw new Error('PDF导出功能需要html2pdf.js库支持');
    }
  }
  return html2pdf;
};

// 状态变量
const resumes = ref([]);
const loading = ref(true);
const error = ref('');

// 页面加载时获取简历列表
onMounted(() => {
  fetchResumes();
});

// 获取简历列表
const fetchResumes = async () => {
  loading.value = true;
  error.value = '';
  try {
    const response = await axios.get('http://127.0.0.1:8000/resume/resumes/', {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    const data = response.data;
    resumes.value = Array.isArray(data) ? data : [];
    console.log('获取到的简历数据:', resumes.value);
  } catch (err) {
    console.error('获取简历列表失败:', err);
    if (err.response && err.response.status === 404) {
      error.value = '接口不存在，请检查后端路由配置';
    } else if (err.message && (err.message.includes('Network Error') || err.message.includes('ERR_CONNECTION_REFUSED'))) {
      error.value = '无法连接到服务器，请检查后端是否启动（http://127.0.0.1:8000）！';
    } else {
      error.value = '加载简历失败：' + (err.message || '未知错误');
    }
  } finally {
    loading.value = false;
  }
};

// 格式化简历内容为HTML
const formatResumeToHTML = (resume) => {
  let html = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>${resume.name} - 个人简历</title>
      <style>
        body {
          font-family: "Microsoft YaHei", "SimSun", Arial, sans-serif;
          line-height: 1.6;
          color: #333;
          max-width: 800px;
          margin: 0 auto;
          padding: 20px;
        }
        .header {
          text-align: center;
          border-bottom: 2px solid #42b983;
          padding-bottom: 20px;
          margin-bottom: 30px;
        }
        .header h1 {
          margin: 0;
          color: #42b983;
          font-size: 28px;
        }
        .section {
          margin-bottom: 30px;
        }
        .section-title {
          font-size: 20px;
          color: #42b983;
          border-left: 4px solid #42b983;
          padding-left: 10px;
          margin-bottom: 15px;
        }
        .info-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 10px;
          margin-bottom: 20px;
        }
        .info-item {
          display: flex;
        }
        .info-label {
          font-weight: bold;
          width: 100px;
        }
        .experience-item {
          margin-bottom: 20px;
          padding-left: 15px;
          border-left: 3px solid #42b983;
        }
        .experience-header {
          font-weight: bold;
          font-size: 16px;
          margin-bottom: 5px;
        }
        .experience-date {
          color: #666;
          font-size: 14px;
          margin-bottom: 5px;
        }
        .experience-content {
          color: #555;
          margin-top: 5px;
        }
      </style>
    </head>
    <body>
      <div class="header">
        <h1>${resume.name || '个人简历'}</h1>
      </div>
      
      <div class="section">
        <div class="section-title">基本信息</div>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">姓名：</span>
            <span>${resume.name || '无'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">应届年份：</span>
            <span>${resume.graduate_year || '无'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">学历：</span>
            <span>${resume.education || '无'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">求职状态：</span>
            <span>${resume.job_status || '无'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">手机号：</span>
            <span>${resume.phone || '无'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">期望职位：</span>
            <span>${resume.expectedJob || '无'}</span>
          </div>
          <div class="info-item">
            <span class="info-label">简历评分：</span>
            <span>${resume.resume_score || 0}分</span>
          </div>
          <div class="info-item">
            <span class="info-label">待优化项：</span>
            <span>${resume.optimization_items || 0}项</span>
          </div>
        </div>
        ${resume.preponderance ? `<div class="info-item"><span class="info-label">个人优势：</span><span>${resume.preponderance}</span></div>` : ''}
      </div>
  `;

  // 工作经历
  if (resume.work_experiences && resume.work_experiences.length > 0) {
    html += `
      <div class="section">
        <div class="section-title">工作/实习经历</div>
    `;
    resume.work_experiences.forEach(exp => {
      html += `
        <div class="experience-item">
          <div class="experience-header">${exp.company || '无'} - ${exp.position || '无'}</div>
          <div class="experience-date">${exp.start_date || '无'} ~ ${exp.end_date || '至今'}</div>
          <div class="experience-content">${exp.description || '无'}</div>
        </div>
      `;
    });
    html += `</div>`;
  }

  // 项目经历
  if (resume.project_experiences && resume.project_experiences.length > 0) {
    html += `
      <div class="section">
        <div class="section-title">项目经历</div>
    `;
    resume.project_experiences.forEach(exp => {
      html += `
        <div class="experience-item">
          <div class="experience-header">${exp.project_name || '无'} - ${exp.role || '无'}</div>
          <div class="experience-date">${exp.start_date || '无'} ~ ${exp.end_date || '至今'}</div>
          <div class="experience-content">${exp.description || '无'}</div>
        </div>
      `;
    });
    html += `</div>`;
  }

  // 教育经历
  if (resume.education_experiences && resume.education_experiences.length > 0) {
    html += `
      <div class="section">
        <div class="section-title">教育经历</div>
    `;
    resume.education_experiences.forEach(exp => {
      html += `
        <div class="experience-item">
          <div class="experience-header">${exp.school || '无'} - ${exp.education || '无'}</div>
          <div class="experience-date">${exp.start_date || '无'} ~ ${exp.end_date || '无'}</div>
          ${exp.major ? `<div class="experience-content"><strong>专业：</strong>${exp.major}</div>` : ''}
          ${exp.description ? `<div class="experience-content">${exp.description}</div>` : ''}
        </div>
      `;
    });
    html += `</div>`;
  }

  html += `
    </body>
    </html>
  `;
  return html;
};

// 导出单个简历为Word
const exportSingleAsWord = async (resume) => {
  try {
    const html = formatResumeToHTML(resume);
    
    // 创建Blob对象
    const blob = new Blob(['\ufeff', html], { type: 'application/msword' });
    const url = URL.createObjectURL(blob);
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = url;
    link.download = `${resume.name || '简历'}_${resume.id}.doc`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    alert('Word文件导出成功！');
  } catch (err) {
    console.error('导出Word失败:', err);
    alert('导出Word失败：' + err.message);
  }
};

// 导出单个简历为PDF
const exportSingleAsPDF = async (resume) => {
  try {
    // 加载html2pdf库
    const html2pdfLib = await loadHtml2Pdf();
    
    const html = formatResumeToHTML(resume);
    const element = document.createElement('div');
    element.innerHTML = html;
    element.style.position = 'absolute';
    element.style.left = '-9999px';
    element.style.width = '800px';
    document.body.appendChild(element);
    
    const opt = {
      margin: [10, 10, 10, 10],
      filename: `${resume.name || '简历'}_${resume.id}.pdf`,
      image: { type: 'jpeg', quality: 0.98 },
      html2canvas: { 
        scale: 2, 
        useCORS: true,
        logging: false,
        windowWidth: 800
      },
      jsPDF: { 
        unit: 'mm', 
        format: 'a4', 
        orientation: 'portrait' 
      }
    };
    
    await html2pdfLib().set(opt).from(element).save();
    document.body.removeChild(element);
    
    alert('PDF文件导出成功！');
  } catch (err) {
    console.error('导出PDF失败:', err);
    alert('导出PDF失败：' + (err.message || '未知错误'));
  }
};

// 导出全部简历为Word
const exportAllAsWord = async () => {
  if (resumes.value.length === 0) {
    alert('没有可导出的简历');
    return;
  }
  
  try {
    let allHtml = '';
    resumes.value.forEach((resume, index) => {
      const html = formatResumeToHTML(resume);
      // 移除HTML的head和body标签，只保留内容
      const content = html.replace(/<!DOCTYPE[^>]*>/, '')
                          .replace(/<html[^>]*>/, '')
                          .replace(/<\/html>/, '')
                          .replace(/<head>[\s\S]*?<\/head>/, '')
                          .replace(/<body[^>]*>/, '')
                          .replace(/<\/body>/, '');
      
      if (index > 0) {
        allHtml += '<div style="page-break-before: always;"></div>';
      }
      allHtml += content;
    });
    
    // 添加完整的HTML结构
    const fullHtml = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <title>全部简历导出</title>
        <style>
          body {
            font-family: "Microsoft YaHei", "SimSun", Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
          }
          .header {
            text-align: center;
            border-bottom: 2px solid #42b983;
            padding-bottom: 20px;
            margin-bottom: 30px;
          }
          .header h1 {
            margin: 0;
            color: #42b983;
            font-size: 28px;
          }
          .section {
            margin-bottom: 30px;
          }
          .section-title {
            font-size: 20px;
            color: #42b983;
            border-left: 4px solid #42b983;
            padding-left: 10px;
            margin-bottom: 15px;
          }
          .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-bottom: 20px;
          }
          .info-item {
            display: flex;
          }
          .info-label {
            font-weight: bold;
            width: 100px;
          }
          .experience-item {
            margin-bottom: 20px;
            padding-left: 15px;
            border-left: 3px solid #42b983;
          }
          .experience-header {
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 5px;
          }
          .experience-date {
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
          }
          .experience-content {
            color: #555;
            margin-top: 5px;
          }
        </style>
      </head>
      <body>
        ${allHtml}
      </body>
      </html>
    `;
    
    const blob = new Blob(['\ufeff', fullHtml], { type: 'application/msword' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `全部简历_${new Date().getTime()}.doc`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    alert(`成功导出${resumes.value.length}份简历为Word文件！`);
  } catch (err) {
    console.error('导出全部Word失败:', err);
    alert('导出全部Word失败：' + err.message);
  }
};

// 导出全部简历为PDF
const exportAllAsPDF = async () => {
  if (resumes.value.length === 0) {
    alert('没有可导出的简历');
    return;
  }
  
  try {
    // 加载html2pdf库
    const html2pdfLib = await loadHtml2Pdf();
    
    // 逐个导出PDF
    for (let i = 0; i < resumes.value.length; i++) {
      const resume = resumes.value[i];
      const html = formatResumeToHTML(resume);
      const element = document.createElement('div');
      element.innerHTML = html;
      element.style.position = 'absolute';
      element.style.left = '-9999px';
      element.style.width = '800px';
      document.body.appendChild(element);
      
      const opt = {
        margin: [10, 10, 10, 10],
        filename: `${resume.name || '简历'}_${resume.id}.pdf`,
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { 
          scale: 2, 
          useCORS: true,
          logging: false,
          windowWidth: 800
        },
        jsPDF: { 
          unit: 'mm', 
          format: 'a4', 
          orientation: 'portrait' 
        }
      };
      
      await html2pdfLib().set(opt).from(element).save();
      document.body.removeChild(element);
      
      // 添加延迟，避免浏览器阻止多个下载
      if (i < resumes.value.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 500));
      }
    }
    
    alert(`成功导出${resumes.value.length}份简历为PDF文件！`);
  } catch (err) {
    console.error('导出全部PDF失败:', err);
    alert('导出全部PDF失败：' + (err.message || '未知错误'));
  }
};

// 返回列表页
const goBack = () => {
  router.push('/resume');
};
</script>

<style scoped>
.export-container {
  width: 100%;
  padding: 20px;
}

.export-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  color: #333;
  font-size: 24px;
  margin: 0;
  font-weight: 600;
  flex: 1;
}

.export-actions {
  display: flex;
  gap: 10px;
}

.loading-container,
.error-container {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

.error-container {
  color: #ff4d4f;
}

.error-text {
  margin: 20px 0;
  font-size: 16px;
}

.resume-list {
  margin-top: 20px;
}

.empty-container {
  text-align: center;
  padding: 80px 20px;
  color: #999;
}

.empty-text {
  font-size: 18px;
  margin-bottom: 10px;
}

.empty-hint {
  font-size: 14px;
  color: #ccc;
}

.resume-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.resume-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.resume-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-title h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.card-badge {
  background: #42b983;
  color: #fff;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.card-body {
  margin-top: 15px;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
  font-size: 14px;
}

.info-label {
  width: 100px;
  color: #666;
  font-weight: 500;
}

.info-value {
  color: #333;
  flex: 1;
}

.info-tags {
  display: flex;
  gap: 10px;
  margin-top: 15px;
  flex-wrap: wrap;
}

.tag {
  background: #f0f0f0;
  color: #666;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #666;
}

.btn-secondary:hover:not(:disabled) {
  background-color: #e5e5e5;
}

.btn-primary {
  background-color: #42b983;
  color: #ffffff;
}

.btn-primary:hover:not(:disabled) {
  background-color: #359469;
}

.btn-success {
  background-color: #52c41a;
  color: #ffffff;
}

.btn-success:hover:not(:disabled) {
  background-color: #41a616;
}

.btn-danger {
  background-color: #ff4d4f;
  color: #ffffff;
}

.btn-danger:hover:not(:disabled) {
  background-color: #ff7875;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

@media (max-width: 768px) {
  .export-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .export-actions {
    width: 100%;
    flex-direction: column;
  }
  
  .export-actions .btn {
    width: 100%;
  }
  
  .resume-cards {
    grid-template-columns: 1fr;
  }
}
</style>

